package com.jkoss.wine.investment.service.impl;

import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.CryptoUtils;
import com.jkoss.common.util.UuidUtil;
import com.jkoss.wine.investment.entity.Handover;
import com.jkoss.wine.investment.mapper.HandoverMapper;
import com.jkoss.wine.investment.service.IHandoverService;
import com.jkoss.wine.investment.vo.HandoverVo;
import com.jkoss.wine.merchant.entity.MerchantProduct;
import com.jkoss.wine.merchant.entity.MerchantProductNorm;
import com.jkoss.wine.merchant.entity.MerchantProductType;
import com.jkoss.wine.merchant.mapper.MerchantProductMapper;
import com.jkoss.wine.merchant.mapper.MerchantProductNormMapper;
import com.jkoss.wine.merchant.mapper.MerchantProductTypeMapper;
import com.jkoss.wine.shop.entity.Distribution;
import com.jkoss.wine.shop.entity.InventoryWarning;
import com.jkoss.wine.shop.entity.Product;
import com.jkoss.wine.shop.entity.ProductInventory;
import com.jkoss.wine.shop.entity.ProductNorm;
import com.jkoss.wine.shop.entity.ProductType;
import com.jkoss.wine.shop.entity.Shop;
import com.jkoss.wine.shop.entity.ShopAccounts;
import com.jkoss.wine.shop.entity.ShopEmployees;
import com.jkoss.wine.shop.entity.ShopSetting;
import com.jkoss.wine.shop.mapper.DistributionMapper;
import com.jkoss.wine.shop.mapper.InventoryWarningMapper;
import com.jkoss.wine.shop.mapper.ProductInventoryMapper;
import com.jkoss.wine.shop.mapper.ProductMapper;
import com.jkoss.wine.shop.mapper.ProductNormMapper;
import com.jkoss.wine.shop.mapper.ProductTypeMapper;
import com.jkoss.wine.shop.mapper.ShopAccountsMapper;
import com.jkoss.wine.shop.mapper.ShopEmployeesMapper;
import com.jkoss.wine.shop.mapper.ShopMapper;
import com.jkoss.wine.shop.mapper.ShopSettingMapper;

import cn.afterturn.easypoi.exception.excel.ExcelExportException;

import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 新客户基本情况交接表 服务实现类
 * 
 * @Author Jason
 * @Version 1.0, 2018-11-25
 * @See
 * @Since com.jkoss.wine.investment.service.impl
 * @Description: TODO
 */
@Service
public class HandoverServiceImpl extends ServiceImpl<HandoverMapper, Handover> implements IHandoverService {
	@Autowired
	private ShopMapper shopMapper;
	@Autowired
	private ShopEmployeesMapper shopEmployeesMapper;

	@Autowired
	private ShopAccountsMapper shopAccountsMapper;

	@Autowired
	private MerchantProductTypeMapper merchantProductTypeMapper;
	@Autowired
	private ProductTypeMapper productTypeMapper;
	@Autowired
	private MerchantProductMapper merchantProductMapper;
	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private InventoryWarningMapper inventoryWarningMapper;

	@Autowired
	private MerchantProductNormMapper merchantProductNormMapper;
	@Autowired
	private ProductNormMapper productNormMapper;
	@Autowired
	private ProductInventoryMapper productInventoryMapper;
	@Autowired
	private DistributionMapper distributionMapper;
	@Autowired
	private ShopSettingMapper shopSettingMapper;

	@Override
	public Page selectVoPage(Page page, Wrapper wrapper) {
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoPage(page, wrapper));
		return page;
	}

	@Override
	public boolean updateState(Handover handover) throws Exception {
		// 状态：1-申请移交、2-移交通过、3-移交不通过
		if (handover.getState() == 2) {
			Handover handover2 = baseMapper.selectById(handover.getId());

			Shop shop = new Shop();
			Integer maxShopNum = shopMapper.getMaxShopNum();
			if (maxShopNum == null) {
				maxShopNum = 0;
			}
			maxShopNum += 1;
			// 店铺编号
			shop.setShopNum(maxShopNum.toString());
			// 店铺密码
			shop.setOperatingPwd(CryptoUtils.encodeMD5("123456"));
			// 财务
			shop.setBelongs(handover.getOperator());
			// 操作人
			shop.setOperator(handover.getOperator());
			// 添加时间
			shop.setAddTime(CommonUtil.getDate());
			// 是否删除：0-未删除、1-已删除、2-不能删除
			shop.setDel(0);
			// 店铺状态：0-停用、 1-启用
			shop.setShopState(1);
			// 门店状态：1-新客户、2-门店建设中、3-门店配货中、4-常规客户
			shop.setState(1);
			// 复制手机号码
			shop.setMobilePhone(handover2.getPhone());
			// 联系电话
			shop.setContactNumber(handover2.getPhone());
			// 地址
			shop.setAddress(handover2.getAddr());
			// 地区编码
			shop.setAreaCode(handover2.getAreaCode());
			// 地区
			shop.setAreaName(handover2.getAreaName());
			// 合同编号
			shop.setCtno(handover2.getCtno());
			// 店铺面积
			shop.setFtae(handover2.getFtae());
			// 招商经理
			shop.setImid(handover2.getImid());
			// 客户来源
			shop.setSource(handover2.getSource());
			// 签约时间
			shop.setSgtm(handover2.getSgtm());
			// 店面级别
			shop.setStle(handover2.getStle());
			// 区域经理
			shop.setRgid(handover2.getRgid());
			// 运营督导
			shop.setOpid(handover2.getOpid());
			// 店铺名称
			shop.setShopName(handover2.getName());
			// 联系人名称
			shop.setContacts(handover2.getName());
			if (retBool(shopMapper.insert(shop))) {
				// region 添加ShopEmployees
				ShopEmployees shopEmployees = new ShopEmployees();
				shopEmployees.setShopId(shop.getShopId());
				shopEmployees.setEmployeeName(shop.getContacts());
				shopEmployees.setEmployeeSex(1);
				shopEmployees.setEmployeePhone(shop.getMobilePhone());
				shopEmployees.setAddTime(CommonUtil.getDate());
				shopEmployees.setOperator(shop.getOperator());
				if (!retBool(shopEmployeesMapper.insert(shopEmployees))) {
					throw new Exception("门店雇员新增失败");
				}
				// endregion

				// region 添加ShopAccounts
				ShopAccounts shopAccounts = new ShopAccounts();
				shopAccounts.setShopId(shop.getShopId());
				shopAccounts.setEmployeeId(shopEmployees.getEmployeeId());
				shopAccounts.setAccountNum(shop.getMobilePhone());
				shopAccounts.setAccountPwd(CryptoUtils.encodeMD5("123456"));
				shopAccounts.setAddTime(CommonUtil.getDate());
				shopAccounts.setOperator(shop.getOperator());
				shopAccounts.setPowerStr(shopMapper.getShopAllFunction()); // 新开店铺给所有权限
				shopAccounts.setAccountState(1);
				if (!retBool(shopAccountsMapper.insert(shopAccounts))) {
					throw new Exception("门店雇员帐号新增失败");
				}
				// endregion

				// region 商品类型复制
				List<MerchantProductType> merchantProductTypes = merchantProductTypeMapper.selectList(null);
				List<ProductType> productTypes = new ArrayList<>();
				for (MerchantProductType item : merchantProductTypes) {
					ProductType temp = new ProductType();
					BeanUtils.copyProperties(item, temp);
					temp.setProductTypeId(UuidUtil.getUUID());
					temp.setParentId(item.getMerchantProductTypeId());
					temp.setShopId(shop.getShopId());
					productTypes.add(temp);
				}
				if (productTypes.size() > 0) {
					if (!retBool(productTypeMapper.insertBatch(productTypes))) {
						throw new Exception("商品类型复制失败");
					}
				}
				// endregion

				// 商品复制
				List<MerchantProduct> merchantProducts = merchantProductMapper.selectList(null);
				List<Product> products = new ArrayList<>();
				for (MerchantProduct item : merchantProducts) {
					Product temp = new Product();
					BeanUtils.copyProperties(item, temp);
					temp.setProductId(UuidUtil.getUUID());
					temp.setParentId(item.getMerchantProductId());
					temp.setShopId(shop.getShopId());
					temp.setProductTypeId(getProductTypeId(productTypes, item.getMerchantProductTypeId()));
					temp.setFreightPrice(0);
					products.add(temp);
				}
				if (products.size() > 0) {
					if (!retBool(productMapper.insertBatch(products))) {
						throw new Exception("商品复制失败");
					}
				}

				// region 商品规格复制
				List<MerchantProductNorm> merchantProductNorms = merchantProductNormMapper.selectList(null);
				List<ProductNorm> productNorms = new ArrayList<>();
				for (MerchantProductNorm item : merchantProductNorms) {
					ProductNorm temp = new ProductNorm();
					BeanUtils.copyProperties(item, temp);
					temp.setProductNormId(UuidUtil.getUUID());
					temp.setParentId(item.getMerchantProductNormId());
					temp.setProductId(getProductId(products, item.getMerchantProductId()));
					temp.setShopId(shop.getShopId());
					temp.setNormPrice(item.getSuggestedPrice());
					productNorms.add(temp);
				}
				if (productNorms.size() > 0) {
					if (!retBool(productNormMapper.insertBatch(productNorms))) {
						throw new Exception("商品规格复制失败");
					}
				}
				// endregion

				// TODO: 2018/5/22 总店没有库存概念，后期可能会加，业务上也不是直接复制

				// 商品库存复制
				List<ProductInventory> productInventories = new ArrayList<>();
				for (ProductNorm item : productNorms) {
					ProductInventory temp = new ProductInventory();
					temp.setProductInventoryId(UuidUtil.getUUID());
					temp.setProductNormId(item.getProductNormId());
					temp.setProductId(item.getProductId());
					temp.setShopId(item.getShopId());
					temp.setInventory(0);
					temp.setInventoryNum(null);
					temp.setType(0);
					temp.setOperator(null);
					temp.setAddTime(CommonUtil.getDate());
					temp.setRemark("创建商品自动入库");

					productInventories.add(temp);
				}
				if (productInventories.size() > 0) {
					if (!retBool(productInventoryMapper.insertBatch(productInventories))) {
						throw new Exception("创建商品自动入库失败");
					}
				}

				// 商品库存预警复制
				List<InventoryWarning> inventoryWarnings = new ArrayList<>();
				for (ProductNorm item : productNorms) {
					InventoryWarning temp = new InventoryWarning();
					BeanUtils.copyProperties(item, temp);
					temp.setInventoryWarningId(UuidUtil.getUUID());
					temp.setShopId(shop.getShopId());
					temp.setWarningValue(0);
					inventoryWarnings.add(temp);
				}
				if (inventoryWarnings.size() > 0) {
					if (!retBool(inventoryWarningMapper.insertBatch(inventoryWarnings))) {
						throw new Exception("商品库存预警复制失败");
					}
				}
				// region 分销设置
				Distribution distribution = new Distribution();
				distribution.setDistributionId(UuidUtil.getUUID());
				distribution.setUlBackPercent(0);
				distribution.setOlBackPercent(0);
				distribution.setOlDiscount(100);
				distribution.setOperationTime(CommonUtil.getDate());
				distribution.setOperator(shop.getOperator());
				distribution.setShopId(shop.getShopId());
				if (!retBool(distributionMapper.insert(distribution))) {
					throw new Exception("初始化分销设置失败");
				}
				// endregion
				// region 店铺设置
				ShopSetting shopSetting = new ShopSetting();
				shopSetting.setShopSettingId(UuidUtil.getUUID());
				shopSetting.setShopId(shop.getShopId());
				shopSetting.setOperator(shop.getOperator());
				shopSetting.setOnlineSaleType(0);
				shopSetting.setRechargeAllowGive(0);
				shopSetting.setAddTime(CommonUtil.getDate());
				if (!retBool(shopSettingMapper.insert(shopSetting))) {
					throw new Exception("店铺设置失败");
				}
				// endregion
			}
		}
		if (!retBool(baseMapper.updateById(handover))) {
			throw new Exception("审核失败");
		}
		return true;
	}

	@Override
	public HandoverVo selectVoById(String id) {
		return baseMapper.selectVoById(id);
	}

	private String getProductTypeId(List<ProductType> source, String parentId) {
		if (source != null) {
			for (ProductType productType : source) {
				if (productType.getParentId().equals(parentId)) {
					return productType.getProductTypeId();
				}
			}
		}
		return null;
	}

	private String getProductId(List<Product> source, String parentId) {
		if (source != null) {
			for (Product product : source) {
				if (product.getParentId().equals(parentId)) {
					return product.getProductId();
				}
			}
		}
		return null;
	}
}
